package com.kun.video.ui;

import cn.hutool.core.util.StrUtil;
import com.kun.video.ui.control.button.AbstractButton;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.event.EventType;
import javafx.scene.Node;
import javafx.scene.control.Control;
import javafx.scene.control.Tooltip;

/**
 * TODO
 *
 * @author gzc
 * @since 2025/3/10
 **/
public class ComponentUtil {

    public static void setTooltip(Control control, String tooltipText) {
        if (control != null && StrUtil.isNotBlank(tooltipText)) {
            control.setTooltip(new Tooltip(tooltipText));
        }
    }

    /**
     * 释放资源方法
     *
     * @param resourceObj 资源对象
     */
    public static void dispose(Object resourceObj) {
        if (resourceObj instanceof KunComponent kunComponent) {
            kunComponent.dispose();
        }
    }

    /**
     * 通用弱引用监听器注册方法
     */
    public static <T> void weakChangeListener(ObservableValue<T> property, ChangeListener<? super T> listener) {
//        property.addListener(new WeakChangeListener<>(listener));
        property.addListener(listener);
    }

    public static <T extends Event> void weakActionEventHandler(Node node, EventType<T> eventType, EventHandler<? super T> eventHandler) {
        if (node != null) {
            node.addEventHandler(eventType, eventHandler);
        }
    }

    public static <T extends Event> void weakActionEventHandler(AbstractButton abstractButton, Runnable runnable) {
        if (abstractButton != null) {
            abstractButton.action(runnable);
        }
    }

    public static <T extends Event> void weakActionEventHandler(AbstractButton abstractButton, EventHandler<? super T> eventHandler) {
        if (abstractButton != null) {
            abstractButton.action(() -> eventHandler.handle(null));
        }
    }

    public static <T> void removeWeakListener(ObservableValue<T> property, ChangeListener<? super T> listener) {
        property.removeListener(listener);
    }


    public static <T extends Event> void removeWeakListener(Node node, EventType<T> eventType, EventHandler<? super T> eventHandler) {
        if (node != null) {
            node.removeEventHandler(eventType, eventHandler);
        }
    }

    public static <T extends Event> void removeWeakListener(AbstractButton abstractButton, Runnable runnable) {
        if (abstractButton != null) {
            abstractButton.clearEvent(runnable);
        }
    }

    public static <T extends Event> void removeWeakListener(AbstractButton abstractButton, EventHandler<? super T> eventHandler) {
        if (abstractButton != null) {
            abstractButton.clearEvent(null);
        }
    }

}
